
/**
 * Compare wechat or sdk version function, from wechat official
 * if (v1 > v2) return 1, v1 < v2 return -1, v1 === v2 return 0
 */
import { reportMonitor,reportError } from './report'
export function compareVersion(v1, v2) {
  v1 = v1.split('.');
  v2 = v2.split('.');
  var len = Math.max(v1.length, v2.length);

  while (v1.length < len) {
    v1.push('0');
  }
  while (v2.length < len) {
    v2.push('0');
  }

  for (var i = 0; i < len; i++) {
    var num1 = parseInt(v1[i]);
    var num2 = parseInt(v2[i]);

    if (num1 > num2) {
      return 1;
    } else if (num1 < num2) {
      return -1;
    }
  }

  return 0;
}

/**
 * custom showModal
 */
export function showModal (title, content) {
  uni.showModal({
    title: title,
    content: content.replace(/(^\s*)|(\s*$)/g, ''),
    showCancel: false,
    confirmText: '我知道了',
    confirmColor: '#2d72f1',
    success: function (res) {
      if (res.confirm) {
      } else if (res.cancel) {
      }
    },
  });
};



// 开始微信原生验证
// http://dcloud.oa.com/wiki/WxFace/20608
// WxVerifyTypeIsVideo: false //是否使用微信原生上传核验视频接口，默认值 false
export let nativeVerify = (
  WxVerifyTypeIsVideo,
  WxCheckAliveType,
  baseUrl,
  bizToken,
  verifyFailureFunc,
  callback,
) => {
  // 监控上报
  const tag = WxVerifyTypeIsVideo
    ? 'startFacialRecognitionVerifyAndUploadVideo'
    : 'startFacialRecognitionVerify';
  // 1.先获取userIdKey
  getUserIdKey(baseUrl, bizToken, verifyFailureFunc, 
    (userIdKey) => {
    console.log('获取userIdKey成功:', userIdKey);
    let tempFunc = wx.startFacialRecognitionVerify;
    // 2.根据配置，选择是否调用带有视频上传的人脸验证
    if (WxVerifyTypeIsVideo) {
      tempFunc = wx.startFacialRecognitionVerifyAndUploadVideo;
    }
    // 3.开始验证
    tempFunc({
      userIdKey: userIdKey,
      checkAliveType: WxCheckAliveType,
      success(res) {
        // 验证成功
        getWxResult(baseUrl, bizToken, res.verifyResult, res.errCode, res.errMsg, (res) => {
          console.log(res);
          callback(res);
        });
        reportMonitor(bizToken, tag, 0);
      },
      // 验证失败或取消、权限异常时的处理
      fail(err) {
        console.log('getUserIdKey=>',err);
        // 上报异常
        reportError(tag, err);
        // 用户主动取消
        if (err.errCode === 90100) {
          return false;
        }
        // 开发者工具调试或jsapi没权限或一些未知原因异常等情况下会没有errcode
        if (!err.errCode && (err.errCode !== 0)) {
          uni.showModal({
            title: '提示',
            content: err.errMsg,
            showCancel: false,
          });
        } else {
          // 从后台获取验证失败结果回调给客户
          getWxResult(baseUrl, bizToken, err.verifyResult, err.errCode, err.errMsg, (res) => {
            reportMonitor(bizToken, tag, res.ErrorCode || -1);
            callback(res);
          });
        }
      },
    });
  });
};

// 获取userIdKey
let getUserIdKey = async (baseUrl, bizToken, verifyFailureFunc, callback) => {
  try {
    let req = {
      url: `${baseUrl}/api/liveness/getWxUserIdKey?BizToken=${bizToken}`,
    };
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });
    let userIdKey = await getUserIdKeyRequest(req);
    uni.hideLoading();
    // 获取userIdKey 成功
    callback(userIdKey);
  } catch (e) {
    console.log(e);
    uni.hideLoading();
    // 1.如果是14/15错误，直接跳到客户的页面
    if (e.ErrorCode === 15 || e.ErrorCode === 14) {
      if (e.ErrorCode === 15) {
        e.ErrorMsg = '当前BizToken已过期，请重试';
      } else if (e.ErrorCode === 14) {
        e.ErrorMsg = '当前BizToken已验证完成';
      }
      // 直接传给客户
      verifyFailureFunc({
        BizToken: bizToken,
        ErrorCode: e.ErrorCode,
        ErrorMsg: e.ErrorMsg,
      });
    }
    // 2. 接口还未添加到服务器域名，请点击右上角三个点，打开调试模式再试
    else if (e.ErrorCode === -1) {
      uni.showModal({
        title: '提示',
        content: e.ErrorMsg,
        showCancel: false,
      });
    }
    // 3. 其他错误，开启重试逻辑
    else {
      uni.showModal({
        title: '提示',
        content: e.ErrorMsg,
        confirmText: '重试',
        confirmColor: '#2d72f1',
        success: (res) => {
          if (res.confirm) {
            // 如果是重试，走process流程，
            getUserIdKey(baseUrl, bizToken, verifyFailureFunc, callback);
          } else {
            // do not
          }
        },
      });
    }
  }
};

let getUserIdKeyRequest = (req) => {
  console.log(`请求 ${req.url}`);
  return new Promise((resolve, reject) => {
    try {
      uni.request({
        url: req.url,
        method: 'POST',
        data: {},
        success(res) {
          console.log(`request success:`, res.data);
          if (res.data.ErrorCode === 0) {
            // 请求成功，且无错误
            resolve(res.data.Data.UserIdKey);
          } else {
            reject(res.data); // { Data:{}, ErrorCode: 15, ErrorMsg: "token过期，请重试"}
          }
        },
        fail(err) {
          console.log(`requestPromise error:`, err);
          // 如果是网络异常及其他请求错误，reject到重试德逻辑。
          if (
            err.errMsg.indexOf('request:fail Unable to resolve host') >= 0 ||
            err.errMsg.indexOf('request:fail 似乎已断开与互联网的连接') >= 0
          ) {
            reject({ ErrorCode: 101, ErrorMsg: '网络异常，请稍后重试' });
          } else {
            if (err.errMsg === 'request:fail url not in domain list') {
              // 这种情况直接谈个窗就可以了。
              reject({
                ErrorCode: -1,
                ErrorMsg: '接口还未添加到服务器域名，请点击右上角三个点，打开调试模式再试',
              });
            } else {
              reject({ ErrorCode: 101, ErrorMsg: err.errMsg });
            }
          }
        },
      });
    } catch (e) {
      console.log(Raven.captureException(e) + '捕获error');
    }
  });
};

let getWxResult = async (baseUrl, bizToken, verifyResult, errCode, errMsg, callback) => {
  try {
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });
    let res = await getWxResultRequest(baseUrl, bizToken, verifyResult, errCode, errMsg);
    uni.hideLoading();
    callback(res); // 这里包含14/15的错误
  } catch (e) {
    console.log(e);
    uni.hideLoading();
    // 1. 接口还未添加到服务器域名，请点击右上角三个点，打开调试模式再试
    if (e.ErrorCode === -1) {
      uni.showModal({
        title: '提示',
        content: e.ErrorMsg,
        showCancel: false,
      });
    }
    // 2. 其他错误，开启重试逻辑
    else {
      uni.showModal({
        title: '提示',
        content: e,
        confirmText: '重试',
        confirmColor: '#2d72f1',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            // 如果是重试，走process流程，
            getWxResult(baseUrl, bizToken, verifyResult, errCode, errMsg, callback);
          } else {
            // do not
          }
        },
      });
    }
  }
};

let getWxResultRequest = (baseUrl, bizToken, verifyResult, errCode, errMsg) => {
  console.log(`请求 ${baseUrl}/api/liveness/getWxResult?BizToken=${bizToken}`);
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${baseUrl}/api/liveness/getWxResult?BizToken=${bizToken}`,
      method: 'POST',
      data: {
        VerifyResult: verifyResult || '',
        ErrCode: errCode.toString(),
        ErrMsg: errMsg,
      },
      success(res) {
        console.log(`request success:`, res.data);
        if (res.data.ErrorCode === 0) {
          // 请求成功，且无错误
          resolve(res.data);
        } else {
          // 请求到了错误类型
          resolve(res.data); // { Data:{}, ErrorCode: 15, ErrorMsg: "token过期，请重试"}
        }
      },
      fail(err) {
        console.log(`requestPromise error:`, err);
        if (
          err.errMsg.indexOf('request:fail Unable to resolve host') >= 0 ||
          err.errMsg.indexOf('request:fail 似乎已断开与互联网的连接') >= 0
        ) {
          reject({ ErrorCode: 101, ErrorMsg: '网络异常，请稍后重试' });
        } else {
          if (err.errMsg === 'request:fail url not in domain list') {
            reject({
              ErrorCode: -1,
              ErrorMsg: '接口还未添加到服务器域名，请点击右上角三个点，打开调试模式再试',
            });
          } else {
            reject({ ErrorCode: 101, ErrorMsg: err.errMsg });
          }
        }
      },
    });
  });
};


/* module.exports = {
  compareVersion,
  showModal,
  nativeVerify
}; */
